package com.bangda.crm.controller;

import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import com.bangda.crm.domain.CrmClientCondition;
import com.bangda.crm.domain.CrmClientPhone;
import com.bangda.crm.domain.enums.ClientStatusEnum;
import com.bangda.crm.domain.vo.CrmClientPoolVo;
import com.bangda.crm.service.ICrmClientConditionService;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.bangda.crm.domain.CrmClientPool;
import com.bangda.crm.service.ICrmClientPoolService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户公海池Controller
 * 
 * @author fanboshi
 * @date 2023-10-15
 */
@RestController
@RequestMapping("/crm/client_pool")
public class CrmClientPoolController extends BaseController
{
    @Autowired
    private ICrmClientPoolService crmClientPoolService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICrmClientConditionService crmClientConditionService;


/**
 * excel导入客户信息
 *
 * */
@PostMapping("/import")
@ResponseBody
    public AjaxResult importData(@RequestParam("fileUrl") String fileUrl) {
    SysUser sysUser = userService.selectUserByUserName(SecurityUtils.getUsername());
        try {
            // 1. 校验文件地址是否为空
            if (StringUtils.isBlank(fileUrl)) {
                return AjaxResult.error("文件地址不能为空");
            }

            // 2. 校验 URL 格式
            URL url;
            try {
                url = new URL(fileUrl);
            } catch (Exception e) {
                return AjaxResult.error("文件地址格式错误");
            }

            String path = url.getPath();
            if (path == null || path.isEmpty()) {
                return AjaxResult.error("文件地址不正确");
            }

            // 3. 提取文件名并解码
            String filename = path.substring(path.lastIndexOf("/") + 1);
            filename = URLDecoder.decode(filename, StandardCharsets.UTF_8.name());

            // 4. 校验文件格式是否为 Excel
            if (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx")) {
                return AjaxResult.error("仅支持Excel文件");
            }

            // 5. 下载并解析 Excel 文件
            List<CrmClientPoolVo> dataList;
            try (InputStream inputStream = url.openStream()) {
                dataList = EasyExcel.read(inputStream)
                        .head(CrmClientPoolVo.class)
                        .sheet()
                        .doReadSync();
            } catch (Exception e) {
                return AjaxResult.error("下载或解析文件失败：" + e.getMessage());
            }

            // 6. 查询数据库已有客户公司名称（优化查询）
            List<CrmClientPool> existingClients = crmClientPoolService.selectCrmClientPoolList(new CrmClientPool());
            Set<String> existingCompanies = existingClients.stream()
                    .map(CrmClientPool::getClientCompany)
                    .collect(Collectors.toSet());

            // 7. 执行导入逻辑
            List<String> existedList = new ArrayList<>();
            int result = 0;

            for (CrmClientPoolVo client : dataList) {
                if (existingCompanies.contains(client.getClientCompany())) {
                    existedList.add(client.getClientCompany());
                } else {
                    CrmClientPool crmClientPool = new CrmClientPool();
                    crmClientPool.setClientStatus(ClientStatusEnum.BEINCHARGE.getCode());
                    crmClientPool.setCreateBy(sysUser.getNickName());
                    crmClientPool.setKeyboarder(sysUser.getNickName());
                    crmClientPool.setClientVestIn(sysUser.getNickName());
                    crmClientPool.setClientCompany(client.getClientCompany());
                    crmClientPool.setClientIndustry(client.getClientIndustry());
                    crmClientPool.setClientProduct(client.getClientProduct());
                    crmClientPool.setClientAddress(client.getClientAddress());
                    crmClientPool.setClientClassify(client.getClientClassify());
                    ArrayList<CrmClientPhone> crmClientPhones = new ArrayList<>();
                    CrmClientPhone crmClientPhone = new CrmClientPhone();
                    crmClientPhone.setClientPhone(client.getClientPhone());
                    crmClientPhone.setClientName(client.getClientName());
                    crmClientPhones.add(crmClientPhone);
                    crmClientPool.setCrmClientPhoneList(crmClientPhones);
                    result += crmClientPoolService.insertCrmClientPool(crmClientPool);
                    List<CrmClientPool> crmClientPools = crmClientPoolService.selectCrmClientPoolList(crmClientPool);

                    CrmClientCondition crmClientCondition = new CrmClientCondition();
                    crmClientCondition.setClientConditionId( crmClientPools.get(0).getClientId());
                    crmClientCondition.setDetails(client.getDetails());
                    crmClientConditionService.insertCrmClientCondition(crmClientCondition);
                }
            }

            // 8. 返回结果
            if (existedList.isEmpty()) {
                return AjaxResult.success("导入成功，共新增 " + result + " 条记录");
            } else {
                return AjaxResult.success("共有 " + result + " 条导入成功，数据库中已存在的如下：" + existedList);
            }

        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 查重
     * */
    @GetMapping("/chachong")
    public AjaxResult chachong(CrmClientPool crmClientPool)
    {



        crmClientPool.setClientStatus(ClientStatusEnum.BEINCHARGE.getCode());
        List<CrmClientPool> list = crmClientPoolService.chachong(crmClientPool);
        if (list.size()!=0){
            return error("该客户已有同事负责");
        }
        crmClientPool.setClientStatus(null);
        List<CrmClientPool> test = crmClientPoolService.chachong(crmClientPool);
        if (test.size()!=0){
            return success("该客户存在于公海池无人负责");
        }
        return success("此系统不存在该客户");
    }
    /**
     * 查询客户公海池列表
     */

    @GetMapping("/list")
    public TableDataInfo list(CrmClientPool crmClientPool)
    {
        crmClientPool.setClientStatus(ClientStatusEnum.UNMANNED.getCode());
        startPage();
        List<CrmClientPool> list = crmClientPoolService.selectCrmClientPoolList(crmClientPool);
//        TableDataInfo rspData = new TableDataInfo();
//        rspData.setCode(HttpStatus.SUCCESS);
//        rspData.setMsg("查询成功");
//        rspData.setRows(list);
//        rspData.setTotal(new PageInfo(list).getTotal());
        return getDataTable(list);
    }



    //myadminClilist
    @GetMapping("/myadminClilist")
    public TableDataInfo myadminClilist(CrmClientPool crmClientPool)
    {

        crmClientPool.setClientStatus(ClientStatusEnum.BEINCHARGE.getCode());
        startPage();
        List<CrmClientPool> list = crmClientPoolService.selectCrmClientPoolList(crmClientPool);
        return getDataTable(list);
    }

    @GetMapping("/myCrmClilist")
    public TableDataInfo myCrmClilist(CrmClientPool crmClientPool)
    {
        crmClientPool.setClientVestInId(SecurityUtils.getUserId());
        crmClientPool.setClientStatus(ClientStatusEnum.BEINCHARGE.getCode());
        startPage();
        List<CrmClientPool> list = crmClientPoolService.selectCrmClientPoolList(crmClientPool);
        return getDataTable(list);
    }
    //查询所有业务员的名字
    @PostMapping("/getclientVestIn")
    public List<String> getclientVestIn(){
        List<String> list = crmClientPoolService.getclientVestIn();

        return list;

    }
    /**
     * 添加到我的客户
     * */
    @Log(title = "添加为个人的客户", businessType = BusinessType.UPDATE)
    @PostMapping("/addmyclient")
    public AjaxResult addmyclient(@RequestBody CrmClientPool crmClientPool)
    {
        SysUser sysUser = userService.selectUserByUserName(SecurityUtils.getUsername());
        if (StringUtils.isNotNull(sysUser.getNickName())){
            crmClientPool.setClientVestIn(sysUser.getNickName());
        }else {
            crmClientPool.setCreateBy("该用户未设置名字");
        }
        crmClientPool.setClientStatus(ClientStatusEnum.BEINCHARGE.getCode());
        crmClientPool.setClientVestInId(SecurityUtils.getUserId());
        return toAjax(crmClientPoolService.CrmClientPool(crmClientPool));
    }

    /**
     * 移入到公海池
     * */
    @Log(title = "添加为个人的客户", businessType = BusinessType.UPDATE)
    @PostMapping("removeclient")
    public AjaxResult removeclient(@RequestBody CrmClientPool crmClientPool)
    {
        crmClientPool.setClientVestIn("");
        crmClientPool.setClientStatus(ClientStatusEnum.UNMANNED.getCode());
        crmClientPool.setClientVestInId(SecurityUtils.getUserId());
        return toAjax(crmClientPoolService.CrmClientPool(crmClientPool));
    }
    /**
     * 导出客户公海池列表
     */
    @PreAuthorize("@ss.hasPermi('crm:client_pool:export')")
    @Log(title = "客户公海池", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmClientPool crmClientPool)
    {
        List<CrmClientPool> list = crmClientPoolService.selectCrmClientPoolList(crmClientPool);
        ExcelUtil<CrmClientPool> util = new ExcelUtil<CrmClientPool>(CrmClientPool.class);
        util.exportExcel(response, list, "客户公海池数据");
    }

    /**
     * 获取客户公海池详细信息
     */
    @GetMapping(value = "/{clientId}")
    public AjaxResult getInfo(@PathVariable("clientId") Long clientId)
    {

        return success(crmClientPoolService.selectCrmClientPoolByClientId(clientId));
    }

    /**
     * 新增客户公海池
     */
    @Log(title = "客户公海池", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmClientPool crmClientPool)
    {
        CrmClientPool crmClientPool1 = new CrmClientPool();
        crmClientPool1.setClientCompany(crmClientPool.getClientCompany());
        List<CrmClientPool> chachong = crmClientPoolService.chachong(crmClientPool1);
        if (chachong.size()>0){
            return error("该客户已存在");
        }
        if (StringUtils.isNull(crmClientPool.getClientCompany())){
            return error("客户公司名不能为空");
        }
        if (StringUtils.isNull(crmClientPool.getClientIndustry())){
            return error("客户行业不能为空");
        }
        if (StringUtils.isNull(crmClientPool.getClientProduct())){
            return error("客户需求不能为空");
        }
        if (StringUtils.isNull(crmClientPool.getClientClassify())){
            return error("客户类型不能为空");
        }
        if (StringUtils.isNull(crmClientPool.getClientAddress())){
            return error("公司地址不能为空");
        }
        if (crmClientPool.getCrmClientPhoneList().size()==0){
            return error("至少填写一个联系人");
        }
        if (crmClientPool.getCrmClientPhoneList().size()!=0){
            for (CrmClientPhone crmClientPhone : crmClientPool.getCrmClientPhoneList()) {
                if (StringUtils.isNull(crmClientPhone.getClientName()) || "".equals(crmClientPhone.getClientName())){
                    return error("客户名不能为空");
                }
                if (StringUtils.isNull(crmClientPhone.getClientPhone()) || "".equals(crmClientPhone.getClientPhone())){
                    return error("客户电话不能为空");
                }
            }
        }
        return toAjax(crmClientPoolService.insertCrmClientPool(crmClientPool));
    }

    /**
     * 修改客户公海池
     */
    @PreAuthorize("@ss.hasPermi('crm:client_pool:edit')")
    @Log(title = "客户公海池", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmClientPool crmClientPool)
    {
        return toAjax(crmClientPoolService.updateCrmClientPool(crmClientPool));
    }

    /**
     * 删除客户公海池
     */
    @PreAuthorize("@ss.hasPermi('crm:client_pool:remove')")
    @Log(title = "客户公海池", businessType = BusinessType.DELETE)
	@DeleteMapping("/{clientIds}")
    public AjaxResult remove(@PathVariable Long[] clientIds)
    {
        return toAjax(crmClientPoolService.deleteCrmClientPoolByClientIds(clientIds));
    }
}
